package com.xyzwps.ewa.modules.init

import com.xyzwps.ewa.common.Gender
import com.xyzwps.ewa.data.database
import com.xyzwps.ewa.ext.getStringConfig
import com.xyzwps.ewa.modules.auth.password.Password
import com.xyzwps.ewa.modules.auth.password.PasswordRepository
import com.xyzwps.ewa.modules.auth.password.ThePasswordEncryptor
import com.xyzwps.ewa.modules.user.UserInfoForCreating
import com.xyzwps.ewa.modules.user.UserRepository
import com.xyzwps.ewa.modules.user.UserService
import io.ktor.server.application.*
import io.ktor.util.logging.*
import org.jetbrains.exposed.sql.name
import org.jetbrains.exposed.sql.transactions.transaction

private const val DEFAULT_USERNAME = "xyzwps"
private const val DEFAULT_PASSWORD = "123456"

fun Application.init() {
    initDatabase()
    initUser(
        username = environment.getStringConfig("ewa.init.user.username") ?: DEFAULT_USERNAME,
        password = environment.getStringConfig("ewa.init.user.password") ?: DEFAULT_PASSWORD
    )
}

private val log = KtorSimpleLogger("SERVER-INIT")

private fun initDatabase() {
    log.info("Database (${database.name}) url = '${database.url}'")
}

private fun initUser(username: String, password: String) {
    transaction {
        var user = UserRepository.findByUsername(username)
        if (user != null) return@transaction

        user = UserService.create(UserInfoForCreating(name = username, gender = Gender.F))
        PasswordRepository.create(Password(user.id, ThePasswordEncryptor.encrypt(password)))

        log.info("User $username was created.")
    }
}